package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import org.apache.ibatis.annotations.Param;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

     private final String KEY_PREFIX="ly.user.verify:";

     //todo 根据用户名和密码 查询用户信息
    @Override
    public UserDTO queryByUnameAndPwd(String username, String password) {

        //根据用户名查询
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User user = this.getOne(userQueryWrapper);
        if (user == null) { //如果查询不到 报异常
            throw new LyException(400, "用户名错误");
        }
        //用户名查询到之后,校验密码
        if (!passwordEncoder.matches(password,user.getPassword())) {//解密密码不对
            throw new LyException(400, "密码错误");
        }


        return new UserDTO(user);
    }

    //todo 注册账号
    @Override
    @Transactional
    public void logonUser(User user, String code) {
         //先获取存在redis中的key
        String key =KEY_PREFIX+user.getPhone();

        //先校验验证码是否有效
        //redisTemplate.opsForValue().get(key) 取出redis中存的 code ,如果redis中过期了,取不到,也会正常判断不对
        if (StringUtils.isEmpty(code)||!code.equals(redisTemplate.opsForValue().get(key))){
            throw  new LyException(400,"验证码有误");
        }

        //保存到数据库

      /*  //加密测试
        String encode = passwordEncoder.encode("123456");
        //伪解密  首先会根据算法 推测密文的盐值,对着密码的明文加密,加密后匹配两个加密密码信息 这是spring自带的
        passwordEncoder.matches("heima114",encode);
        */

       //对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        this.save(user);

    }


    //todo 发送验证码
    @Override
    public void sendCode(String phone) {

        if (!RegexUtils.isPhone(phone)){//如过参数有误 ,直接报异常
            throw new LyException(400,"请求参数有误");
        }

        Map<String, String> map = new HashMap<>();
        String code = RandomStringUtils.randomNumeric(6);
        map.put("phone",phone);
        map.put("code",code);
                                  // 交换机名称         routing-key    发送的信息
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,map);
        //把验证码 存入redis
        String key =KEY_PREFIX+phone;
        this.redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);//存1分钟

    }

    //todo 判断信息是否存在
    @Override
    public Boolean isExist(String data, Integer type) {
        //根据type 来判断 data是否存在
        String colName = null;
        switch (type) {
            case 1:
                colName = "username";
                if (StringUtils.isEmpty(data)) { //如果data是空 报异常
                    throw new LyException(400, "查询参数有误");
                }
                break;
            case 2:
                colName = "phone";
                if (!RegexUtils.isPhone(data)) {
                    throw new LyException(400, "查询参数有误");
                }
                break;
                default:
                    throw new LyException(400,"查询参数有误");
        }
        //要查询的数据是 data
        Integer count = this.query().eq(colName, data).count();
        return count==1;
    }


    @Autowired
    public JwtUtils jwtUtils;

    //TODO 获取token
    @Override
    public UserDetail checkLogin(String token) {

        Payload payload = jwtUtils.parseJwt(token);
        UserDetail userDetail = payload.getUserDetail();


        return userDetail;
    }


}
